package org.footearth.Restlet.Resource;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.footearth.util.RestletServer;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Form;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import com.alibaba.fastjson.JSON;

public class jsonResp extends ServerResource {

	@Override
	public Representation get() {

		Map<String, String> customers = new HashMap<String, String>();
		customers.put("username_0", "notetime");
		customers.put("username_1", "footearth");
		JsonRepresentation jrep = new JsonRepresentation(
				JSON.toJSONString(customers));
		return jrep;

	}

	@Override
	protected Representation post(Representation entity) {

		// JSONObject json = null;
		// try {
		// json = ((JsonRepresentation) entity).getJsonObject();
		// String name = (String) json.get("name");
		// String address = (String) json.get("address");
		// } catch (JSONException e) {
		// // TODO 自动生成的 catch 块
		// e.printStackTrace();
		// }

		JSONObject json = null;
		try {
			json = new JsonRepresentation(entity).getJsonObject();
		} catch (JSONException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		String name = "";
		String address = "";
		try {
			name = (String) json.get("name");
			address = (String) json.get("address");
		} catch (JSONException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		// {"name":"notetime","address":"footearth"}

		Map<String, String> customers = new HashMap<String, String>();
		customers.put("name", name);
		customers.put("address", address);
		JsonRepresentation jrep = new JsonRepresentation(
				JSON.toJSONString(customers));

		return jrep;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		RestletServer.testResource(8080, "/customers/", jsonResp.class);

	}

}
